package com.sf.wisdomkg.activity;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.sf.wisdomkg.R;
import com.sf.wisdomkg.RecyclerView.RecycleViewDivider;
import com.sf.wisdomkg.adapter.KaoQinListAdapter;
import com.sf.wisdomkg.utils.CommonUtils;
import com.sf.wisdomkg.utils.MyOnItemClickListener;
import com.sf.wisdomkg.xRefreshView.CustomFooterView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

/**
 * Created by Administrator on 2017/9/21.
 */
public class KaoQinDescActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String SHARE_CONTENT = "app_";
    private SharedPreferences setting;

    private String baseUrl = CommonUtils.IP_S+ CommonUtils.M_T;

    private Button back_btn;
    private TextView bar_content;
    private ImageView Near_btn;

    //展示数据
    private RecyclerView recyclerView;
    private XRefreshView xRefreshView;
    private KaoQinListAdapter adapter;
    private LinearLayoutManager layoutManager;
    private ArrayList<HashMap<String, String>> kao_qin_list;

    //时间选择
    private TimePickerView pvCustomTime;


    private String id;
    private String timeStr;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kaoqin);
        getSupportActionBar().hide();

        Bundle bundle = this.getIntent().getExtras();
        id = bundle.getString("id");

        initView();
        initRefreshView();
        initCustomTimePicker();


        bar_content.setText("考勤");
        Near_btn.setVisibility(View.VISIBLE);
        back_btn.setOnClickListener(this);
        Near_btn.setOnClickListener(this);
//        requestData();
//        getKaoQinList();
    }

    /**
     * 初始化UI
     */
    private void initView(){
        setting = this.getSharedPreferences(SHARE_CONTENT,0);
        timeStr = CommonUtils.getStrTime(CommonUtils.getTimeStr());
        if (setting.getString("roleId","").equals("2")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_T;
        }else if (setting.getString("roleId","").equals("3")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_S;
        }else if (setting.getString("roleId","").equals("1")){
            baseUrl = CommonUtils.IP_S + CommonUtils.M_T;
        }


        back_btn = (Button)findViewById(R.id.back_btn);
        bar_content = (TextView)findViewById(R.id.bar_content);
        Near_btn = (ImageView)findViewById(R.id.Near_btn);
        kao_qin_list = new ArrayList<>();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back_btn:
                finish();
                break;
            case R.id.Near_btn:
                pvCustomTime.show();
                break;
        }
    }
    /**
     * 初始化下拉刷新部分
     */
    private void initRefreshView() {
        xRefreshView = (XRefreshView) findViewById(R.id.xrefreshview);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_test_rv);
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new RecycleViewDivider(KaoQinDescActivity.this, LinearLayoutManager.HORIZONTAL, R.drawable.recyclerview_divider));
        adapter = new KaoQinListAdapter(kao_qin_list, KaoQinDescActivity.this);
        // 设置静默加载模式
//        xRefreshView1.setSilenceLoadMore();
        layoutManager = new LinearLayoutManager(KaoQinDescActivity.this);
        recyclerView.setLayoutManager(layoutManager);
        // 静默加载模式不能设置footerview
        recyclerView.setAdapter(adapter);
        //设置刷新完成以后，headerview固定的时间
        xRefreshView.setPinnedTime(1000);
        xRefreshView.setPullLoadEnable(false);
        xRefreshView.setMoveForHorizontal(false);
        xRefreshView.setAutoLoadMore(false);
        xRefreshView.startRefresh();
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {

            @Override
            public void onRefresh(boolean isPullDown) {
                adapter.clear();
                getKaoQinList();

            }

            @Override
            public void onLoadMore(boolean isSilence) {
                xRefreshView.stopLoadMore();


            }
        });
        adapter.setOnItemClickListener(new MyOnItemClickListener() {
            @Override
            public void OnItemClickListener(View view, int position) {
//                Intent intent = new Intent(KaoQinActivity.this,BabyOnlineDescActivity.class);
//                startActivity(intent);
//                String desc = kao_qin_list.get(position).get("item_content");
//                Intent intent = new Intent(KaoQinActivity.this, NongJiaDetailActivity.class);
//                Bundle bundle = new Bundle();
//                bundle.putString("arrayString",desc);
//                intent.putExtras(bundle);
//                startActivity(intent);
            }
        });
    }
    /**
     * 加载数据部分
     */
    public void requestData() {

        if (adapter.getCustomLoadMoreView() == null) {
            adapter.setCustomLoadMoreView(new CustomFooterView(KaoQinDescActivity.this));
        }
        adapter.setData(kao_qin_list);
    }
//    private void setData(){
//        for (int i = 0; i < 10 ; i++){
//            HashMap<String,String> hashMap = new HashMap<>();
//            hashMap.put("item","123");
//            kao_qin_list.add(hashMap);
//        }
//    }

    /**
     * 时间选择器
     */
    private void initCustomTimePicker() {

        /**
         * @description
         *
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2014, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
//                btn_CustomTime.setText(getTime(date));
                    timeStr = getTime(date);
                    adapter.clear();
                    getKaoQinList();
            }
        })
                /*.setType(TimePickerView.Type.ALL)//default is all
                .setCancelText("Cancel")
                .setSubmitText("Sure")
                .setContentSize(18)
                .setTitleSize(20)
                .setTitleText("Title")
                .setTitleColor(Color.BLACK)
               /*.setDividerColor(Color.WHITE)//设置分割线的颜色
                .setTextColorCenter(Color.LTGRAY)//设置选中项的颜色
                .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                .setTitleBgColor(Color.DKGRAY)//标题背景颜色 Night mode
                .setBgColor(Color.BLACK)//滚轮背景颜色 Night mode
                .setSubmitColor(Color.WHITE)
                .setCancelColor(Color.WHITE)*/
               /*.gravity(Gravity.RIGHT)// default is center*/
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        TextView ivCancel = (TextView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})

                .setLabel("年", "月", "日", "时", "分", "秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.LTGRAY)
                .build();

    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     *考勤列表
     */
    private void getKaoQinList() {

        RequestParams params = new RequestParams(baseUrl + "clock/clockdetail");
        params.addParameter("studentId",id);
        params.addParameter("timestamp",timeStr);
        //联网设置
        params.setCacheMaxAge(1000 * 60);
        params.setConnectTimeout(9000);
        System.out.println("得到考勤列表"+params);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("得到考勤列表"+result);
                xRefreshView.stopRefresh();
                xRefreshView.stopLoadMore();
                //解析result
                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject.optString("status").equals("true")) {
                            try {
                                JSONArray jsonArr = new JSONArray(jsonObject.optString("data"));
                                String classType = null;
                                for (int i = 0; i < jsonArr.length(); i++) {
                                    HashMap<String, String> hashMap = new HashMap<>();
                                    JSONObject jsObj = new JSONObject();
                                    jsObj = jsonArr.getJSONObject(i);
                                    hashMap.put("id", jsObj.optString("id"));
                                    hashMap.put("studentId", jsObj.optString("studentId"));

                                    if (!jsObj.optString("startTime").equals("")){
                                        classType = "上课";
                                    }
                                    if (!jsObj.optString("endTime").equals("")){
                                        classType = "下课";
                                    }
                                    hashMap.put("classType", classType);
                                    hashMap.put("startTime", jsObj.optString("startTime"));
                                    hashMap.put("endTime",jsObj.optString("endTime"));
                                    hashMap.put("studentName",jsObj.optString("studentName"));
                                    hashMap.put("className",jsObj.optString("className"));

                                    if (!jsObj.optString("startImg").equals("")){
                                        hashMap.put("img",jsObj.optString("startImg"));
                                    }
                                    if (!jsObj.optString("endImg").equals("")){
                                        hashMap.put("img",jsObj.optString("endImg"));
                                    }

                                    hashMap.put("sex",jsObj.optString("sex"));
                                    hashMap.put("age",jsObj.optString("age"));
                                    kao_qin_list.add(hashMap);
                                }

                                requestData();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }else {
                            Toast.makeText(KaoQinDescActivity.this, "暂无今天的考勤信息！", Toast.LENGTH_SHORT).show();
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                System.out.println("得到的值"+ex);
                Toast.makeText(KaoQinDescActivity.this, "连接服务器失败,请检查网络！" + ex, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                Toast.makeText(KaoQinDescActivity.this, "请求超时,请检查网络！", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                xRefreshView.stopRefresh();
                xRefreshView.stopLoadMore();
            }
        });
    }


}
